package com.hissy.common.office;

import java.io.File;
import java.io.IOException;

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.junit.Test;

/**
 * Created by zhangyanfei on 2018/12/29.
 *
 * @author zhangyanfei
 * @date 2018/12/29
 */
public class PdfUtil {

    public void readFileOfPDF(String pdfName) throws IOException {
        int endPage;
        int startPage = 1;
        File file = new File(pdfName);
        System.out.println(file.exists());
        PDDocument document = PDDocument.load(file);
        PDFTextStripper pts = new PDFTextStripper();
        endPage = document.getNumberOfPages();
        System.out.println("Total Page: " + endPage);
        pts.setStartPage(startPage);
        pts.setEndPage(endPage);
        try {
            //content就是从pdf中解析出来的文本
            String content = pts.getText(document);
            System.out.println(content);
        } catch (Exception e) {
            throw e;
        } finally {
            document.close();
        }
    }

    @Test
    public void test() throws IOException {
        readFileOfPDF("12.pdf");
        readFileOfPDF_Itext("12.pdf");
    }

    public void readFileOfPDF_Itext(String fileName) {
        try {
            PdfReader reader = new PdfReader(fileName);
            String content = PdfTextExtractor.getTextFromPage(reader, 1);
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
